const mysql = require('mysql2/promise');

async function main() {
    const args = process.argv.slice(2);
    let id = 0, itemId = 0, num = 1;
    for (let i = 0; i < args.length; i++) {
        if (args[i] === '--id' && args[i + 1]) id = parseInt(args[i + 1], 10);
        if (args[i] === '--item' && args[i + 1]) itemId = parseInt(args[i + 1], 10);
        if (args[i] === '--num' && args[i + 1]) num = parseInt(args[i + 1], 10);
    }
    if (!id || !itemId || !num) {
        console.error('用法: node scripts/grant-item.js --id 2001 --item 83 --num 5');
        process.exit(1);
    }

    const db = {
        host: process.env.DB_HOST || '43.143.253.188',
        port: parseInt(process.env.DB_PORT || '3306', 10),
        user: process.env.DB_USER || 'nextjs',
        password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
        database: process.env.DB_NAME || 'nextjs',
    };

    let conn;
    try {
        conn = await mysql.createConnection(db);
        const [row] = await conn.execute('SELECT id, num, status FROM character_inventory WHERE characterId = ? AND itemId = ? LIMIT 1', [id, itemId]);
        if (row && row[0]) {
            const current = Number(row[0].num || 0);
            await conn.execute('UPDATE character_inventory SET num = ?, status = 1, updated_at = NOW() WHERE id = ?', [current + num, row[0].id]);
            console.log(`已叠加物品 ${itemId} 数量=${num} 至角色 ${id}`);
        } else {
            await conn.execute('INSERT INTO character_inventory (characterId, itemId, num, status, created_at, updated_at) VALUES (?, ?, ?, 1, NOW(), NOW())', [id, itemId, num]);
            console.log(`已发放物品 ${itemId} 数量=${num} 给角色 ${id}`);
        }
    } catch (e) {
        console.error('发放失败:', e && e.message ? e.message : e);
        process.exit(1);
    } finally {
        if (conn) await conn.end();
    }
}

main().catch(e => { console.error(e); process.exit(1); });
